﻿using System;

namespace HK.Core.Utils
{
    
    /// <summary>
    /// 工具类 : Base64.
    /// </summary>
    public static class UtilsBase64
    {
        
        /// <summary>
        /// Base64加密/解密异常
        /// </summary>
        private class Base64Exception : Exception
        {
            public Base64Exception(string message) : base(message) {}
        }

#region Encode

        /// <summary>
        /// Base64加密
        /// </summary>
        /// <param name="iInput">输入</param>
        /// <returns>Base64加密后字符串</returns>
        public static string Base64Encode(byte[] iInput)
        {
            var output = Convert.ToBase64String(iInput);
            output = output.Split('=')[0]; // Remove any trailing '='s
            output = output.Replace('+', '-'); // 62nd char of encoding
            output = output.Replace('/', '_'); // 63rd char of encoding
            return output;
        }

#endregion

#region Decode
        
        /// <summary>
        /// Base64解密
        /// </summary>
        /// <param name="iInput">输入</param>
        /// <returns>解密后的字节数组</returns>
        /// <exception cref="Exception">解密异常</exception>
        public static byte[] Base64Decode(string iInput)
        {
            var output = iInput;
            output = output.Replace('-', '+'); // 62nd char of encoding
            output = output.Replace('_', '/'); // 63rd char of encoding
            switch (output.Length % 4) // Pad with trailing '='s
            {
                case 0: break; // No pad chars in this case
                case 2: output += "=="; break; // Two pad chars
                case 3: output += "="; break;  // One pad char
                default: throw new Base64Exception("Illegal base64 string!");
            }
            var converted = Convert.FromBase64String(output); // Standard base64 decoder
            return converted;
        }

#endregion
    
    }
}